package com.atguigu.elasticsearch.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.Map;

public class ESDocSearch {

    public static void main(String[] args) {

        ESDocSearch search = new ESDocSearch();
        // 1.查询索引中所有文档
//        search.queryAllDataInIndex();

        // 2.条件查询：termQuery
//        search.termQuery();

        // 3. 分页查询
//        search.pageQuery(4, 3);

        // 4. 查询排序
//        search.queryBySort();

        // 5. 过滤字段
//        search.filterField();

        // 6. 组合查询
//        search.combinationQuery();

        // 7. 范围查询

        // 8. 模糊查询
//        search.fuzzyQuery();
        //  9. 高亮查询
//        search.highlightQuery();

        // 10. 聚合查询
        search.aggregationQuery();
    }

    /**
     * 关闭resthighclient
     *
     * @param client
     * @throws IOException
     */
    public void close(RestHighLevelClient client) {
        if (null != client) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建resthighclient对象
     *
     * @return
     */
    public RestHighLevelClient createClient() {
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        return esClient;
    }

    /**
     * 查询索引里所有的数据
     */
    public void queryAllDataInIndex() {

        RestHighLevelClient restHighLevelClient = createClient();

        // 1. 查询索引中全部数据
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user");  // 设置要查询的索引

        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            // 查询匹配的数量
            SearchHits hits = response.getHits();
            System.out.println("took:" + response.getTook());
            System.out.println("timeout:" + response.isTimedOut());
            System.out.println("total:" + hits.getTotalHits());
            System.out.println("max score:" + hits.getMaxScore());
            // 输出每条查询的结果信息
            for (SearchHit hit: hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 精确查询(条件查询)，term关键字
     */
    public void termQuery() {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30)));
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println("total hists:" + hits.getTotalHits());
            System.out.println("took:" + response.getTook()); // 查询花费的时间：took

            for (SearchHit hit : hits) {
                System.out.println("result：" + hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 分页查询
     * @param indexBeginNumber 第一条数据的顺序号
     * @param pageSize 每页查询的数量
     */
    public void pageQuery(Integer indexBeginNumber, Integer pageSize) {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

        // (当前页码-1) * 每页显示数据条数
        builder.from(indexBeginNumber);
        builder.size(pageSize);
        request.source(builder);

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            System.out.println("总的命中数：" + hits.getTotalHits());
            System.out.println("查询消耗时间：" + response.getTook());

            for (SearchHit hit : hits) {
                System.out.println("result:" + hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 查询排序
     */
    public void queryBySort() {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        // 降序排列
        builder.sort("age", SortOrder.DESC);

        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            System.out.println("总的命中数：" + hits.getTotalHits());
            System.out.println("查询消耗时间：" + response.getTook());

            for (SearchHit hit : hits) {
                System.out.println("result:" + hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 过滤字段
     */
    public void filterField() {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

        // 不包括的字段
        String[] excludes = {"age"};
        String[] includes = {}; // 包括的字段，

        builder.fetchSource(includes, excludes);
        request.source(builder);

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            System.out.println("总的命中数：" + hits.getTotalHits());
            System.out.println("查询消耗时间：" + response.getTook());

            for (SearchHit hit : hits) {
                System.out.println("result:" + hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }

    }

    /**
     * 组合查询
     */
    public void combinationQuery() {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
        boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "男"));
        // boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "男"));
        // boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
//        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));

        builder.query(boolQueryBuilder);
        request.source(builder);

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            System.out.println("总的命中数：" + hits.getTotalHits());
            System.out.println("查询消耗时间：" + response.getTook());

            for (SearchHit hit : hits) {
                System.out.println("result:" + hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 范围查询
     */
    public void rangeQuery() {

        RestHighLevelClient esClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");

        rangeQuery.gte(30);
        rangeQuery.lt(50);

        builder.query(rangeQuery);

        request.source(builder);
        SearchResponse response;
        try {
            response = esClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for ( SearchHit hit : hits ) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(esClient);
        }

    }


    /**
     * 模糊查询
     */
    public void fuzzyQuery() {

        RestHighLevelClient restHighLevelClient = createClient();

        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.ONE));

        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            System.out.println("总的命中数：" + hits.getTotalHits());
            System.out.println("查询消耗时间：" + response.getTook());

            for (SearchHit hit : hits) {
                System.out.println("result:" + hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(restHighLevelClient);
        }
    }

    /**
     * 高亮查询
     */
    public void highlightQuery() {

        RestHighLevelClient esClient = createClient();

        SearchRequest request = new SearchRequest().indices("user");

        // 2. 创建查询请求体构建器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 构建查询方式：高亮查询
        TermsQueryBuilder builder = QueryBuilders.termsQuery("name", "zhangsan");

        // 设置查询方式
        sourceBuilder.query(builder);

        // 构建高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>"); // 设置标签前缀
        highlightBuilder.postTags("</font>"); // 设置标签后缀
        highlightBuilder.field("name"); // 设置高亮字段

        // 设置高亮构建对象
        sourceBuilder.highlighter(highlightBuilder);

        // 设置请求体
        request.source(sourceBuilder);

        // 3. 客户端发送请求，获取响应对象
        try {
            SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);


            SearchHits hits = response.getHits();
            System.out.println("took::" + response.getTook());
            System.out.println("time_out::" + response.isTimedOut());
            System.out.println("total::" + hits.getTotalHits());
            System.out.println("max_score::" + hits.getMaxScore());

            for (SearchHit hit: hits) {
                String sourceAsString = hit.getSourceAsString();
                System.out.println(sourceAsString);

                // 打印高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                System.out.println(highlightFields);
            }
            System.out.println("<<::::");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(esClient);
        }
    }

    /**
     * 聚合查询
     */
    public void aggregationQuery() {

        RestHighLevelClient esClient = createClient();

        SearchRequest request = new SearchRequest().indices("user");

        // 聚合查询
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
        // 设置请求体
        request.source(sourceBuilder);
        // 3.客户端发送请求
        try {
            SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

            // 4. 打印响应结果
            SearchHits hits = response.getHits();
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(esClient);
        }
    }

}
